package com.example.demo.exeample;

import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Semaphore;

/**
 * @description: Semaphore原理和实战
 * @time: 2020-10-23 21:16
 * @author: baojinlong
 **/
public class SemaphoreDemo {
    //车位个数
    private static final int PARK_LOT = 2;
    //车辆数
    private static final int CARS = 6;

    private static Semaphore semaphore = new Semaphore(PARK_LOT);

    private static void park() {
        for (int i = 1; i <= CARS; i++) {
            int finalI = i;
            new Thread(() -> {
                try {
                    //看看有没有空车位
                    if (semaphore.availablePermits() == 0) {
                        System.out.println("第" + finalI + "辆司机看了看，哎，还没有空停车位，继续排队");
                    }
                    //尝试进入停车位
                    semaphore.acquire();
                    System.out.println("第" + finalI + "成功进入停车场");
                    Thread.sleep(new Random().nextInt(10000));//模拟车辆在停车场停留的时间
                    System.out.println("第" + finalI + "驶出停车场");
                    //离开停车场
                    semaphore.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }).start();
        }
    }

    public static void main(String[] args) {
        park();
    }
}
